﻿using System;

namespace Jayden.Dll.Core.Persistence
{
	public class Key
	{
		private ObjectType m_Type;
		private object[] m_Values;

		public Key(ObjectType type, object[] values)
		{
			if (type == null)
				throw new ArgumentNullException("type");
			if (values == null)
				throw new ArgumentNullException("values");
			m_Type = type;
			m_Values = values;
		}

		public ObjectType Type { get { return m_Type; } }
		public object this[int index] { get { return m_Values[index]; } set { m_Values[index] = value; } }
		public int Lenght { get { return m_Values == null ? 0 : m_Values.Length; } }

		public override int GetHashCode()
		{
			int hash = m_Type.GetHashCode();
			foreach (object v in m_Values)
			{
				hash *= 0x21;
				if(v != null)
					hash += v.GetHashCode();
			}
			return hash;
		}

		public override bool Equals(object obj)
		{
			if (!(obj is Key))
				return false;
			Key k = obj as Key;
			if (!m_Type.Equals(k.m_Type))
				return false;
			if (m_Values.Length != k.m_Values.Length)
				return false;
			for (int c = 0; c < m_Values.Length; c++)
			{
				if (m_Values[c] == null && k.m_Values[c] == null)
					continue;
				if (m_Values[c] == null)
					return false;
				if (k.m_Values[c] == null)
					return false;
				if (!m_Values[c].Equals(k.m_Values[c]))
					return false;
			}
			return true;
		}

		public override string ToString() { return string.Format("{0}({1})", m_Type, string.Join(", ", m_Values)); }
	}
}
